import pandas as pd
from las.client import LASClient
from las.exceptions import LASError
from las.auth import StaticCredentials
from las.task import SQLTask

# jobid = '2023110812'
# pt_date=jobid[0:8]
# # windows路径
# savepath = './csv/'

def execute_sql_task(ak,sk,sql):
    region = 'cn-beijing'
    endpoint = 'las.volcengineapi.com'
    client = LASClient(credentials=StaticCredentials(ak, sk), region=region,
                       endpoint=endpoint)


    try:
        # timeout 控制超时时间。。
        job = client.execute(task=SQLTask(name='sql task', query=sql, conf={}), is_sync=True,timeout=3000000)
        if job.is_success():
            result = job.get_result()
            return result
    except LASError as e:
        print(
            "Error in executing sql task. code = %s, error = %s" % ( e.code, e.info))

def analysis_total(savepath,pt_version):
    try:
        ak = "AKLTNjI3Y2IxNzc1OGFiNGE5ZmI0YWM1Mzc5MzE3N2IxNzY"
        sk = "TkRJNE56SmxPR1EwTnpNeE5HUmlaR0V5WWpFMU5tRTVOelptWkRNM01tSQ=="

        sql = """
select
package_version,
max(pt_date) as day,
sum(testcase_failed) as fail_case_cnt,
sum(testcase_passed) as passed_case_cnt,
sum(testcase_total) as total_case_cnt
from ods.ods_orin_signal_simulator
where pt_version='{}'
group by package_version
              """
        sql = sql.format(pt_version)
        print("sql: " + sql)
        result = execute_sql_task(ak, sk, sql)
        df_injt = pd.DataFrame(result.data[1:])
        df_injt.columns = result.data[0]

        # 目的是格式化时间并增加send_time 字段。
        if df_injt.shape[0] > 0:
            df_injt.to_pickle(savepath + 'signal_total_version_' + pt_version+'.pkl')
    except Exception as e:
        print('data parse eth error, ', str(e))
def get_version(savepath,pt_date,pt_hour):
    try:
        ak = "AKLTNjI3Y2IxNzc1OGFiNGE5ZmI0YWM1Mzc5MzE3N2IxNzY"
        sk = "TkRJNE56SmxPR1EwTnpNeE5HUmlaR0V5WWpFMU5tRTVOelptWkRNM01tSQ=="

        sql = """
select
pt_version
from ods.ods_orin_signal_simulator
where pt_date='{}'
and pt_hour='{}'
limit 1
              """
        sql = sql.format(pt_date,pt_hour)
        print("sql: " + sql)
        result = execute_sql_task(ak, sk, sql)
        df_injt = pd.DataFrame(result.data[1:])
        df_injt.columns = result.data[0]

        if df_injt.shape[0] > 0:
            df_injt.to_pickle(savepath + 'signal_pt_version_' + pt_date+'_'+pt_hour+'.pkl')

        df_injt['pt_version']=df_injt['pt_version'].astype(str)
        pt_version=str(df_injt['pt_version'].iloc[0])

        return pt_version
    except Exception as e:
        print('data parse eth error, ', str(e))

if __name__ == '__main__':
    pt_date = '20231208'
    pt_hour = '10'
    savepath = '../csv/'
    pt_version=get_version(savepath,pt_date, pt_hour)
    print(pt_version)
    # pt_version_path=savepath + 'signal_pt_version_' + pt_date + '_' + pt_hour + '.pkl'
    # df_pt_version = pd.read_pickle(pt_version_path)
    # df_pt_version['pt_version'] = df_pt_version['pt_version'].astype(str)
    # pt_version = str(df_pt_version['pt_version'].iloc[0])
    # print(pt_version)
    analysis_total(savepath,pt_version)


